<?php

namespace App\Http\Controllers;

use App\Services\BarService;
use App\Services\PostService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class HomeController extends Controller
{
    public function __construct(
        private PostService $postService,
        private BarService $barService
    ) {}

    /**
     * 显示首页
     * 
     * 已登录用户：默认显示关注贴吧的热门帖子，可选择推荐、最新、热门
     * 未登录用户：默认显示热门贴吧的帖子
     */
    public function index(Request $request): Response
    {
        $user = $request->user();
        
        // 根据登录状态确定默认排序
        // 已登录用户：默认关注；未登录用户：默认热门
        $defaultSort = $user ? 'following' : 'hot';
        $sort = $request->input('sort', $defaultSort);
        
        // 未登录用户不能使用"推荐"和"关注"排序
        if (!$user && in_array($sort, ['recommended', 'following'])) {
            $sort = 'hot';
        }
        
        $category = $request->input('category', 'all');
        
        // 从服务层获取热门贴吧（用于侧边栏）
        $popularBars = $this->barService->getPopularBars(5, true);

        // 从服务层获取帖子列表
        $posts = $this->postService->getHomePostsList($sort, 15, $user);

        return Inertia::render('Home', [
            'posts' => $posts,
            'popularBars' => $popularBars,
            'filters' => [
                'sort' => $sort,
                'category' => $category,
            ],
            'isAuthenticated' => (bool) $user,
        ]);
    }
}

